package com.mall.shopping.services;

import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.RedisUtils;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;


@Service
public class ICartServiceImpl implements ICartService {

    @Autowired
    RedissonClient client;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartItemConverter cartItemConverter;

    /**
     * 获得购物车列表
     *
     * @param request
     * @return
     */
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();

        Map map = RedisUtils.redisOfGetMap(client, String.valueOf(request.getUserId()));
        ArrayList<CartProductDto> cartProductDtos = new ArrayList<>();
        if (map != null && map.size() != 0) {
            //此时购物车中有数据
            Set set = map.keySet();
            for (Object o : set) {
                cartProductDtos.add((CartProductDto) map.get(o));
            }
        }

        for (CartProductDto cartItem : cartProductDtos) {
            String imgURL = cartItem.getProductImg();
            if (imgURL != null && !imgURL.isEmpty()) {
                imgURL = imgURL.split(",")[0];
                cartItem.setProductImg(imgURL);
            }
        }

        //此时已经获取到购物车中商品信息
        cartListByIdResponse.setCartProductDtos(cartProductDtos);
        cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return cartListByIdResponse;
    }

    /**
     * 添加商品到购物车
     *
     * @param request
     * @return
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse addCartResponse = new AddCartResponse();
        try {
            //参数校验
            request.requestCheck();
            //获取商品信息
            Item item = itemMapper.selectByPrimaryKey(request.getItemId());
            CartProductDto cartProductDto = cartItemConverter.item2CartProductDto(item);
            cartProductDto.setChecked("false");
            cartProductDto.setProductNum(request.getNum().longValue());
            //将数据存入Redis
            Map map = RedisUtils.redisOfGetMap(client, String.valueOf(request.getUserId()));
            //成功获取信息
            map.put(request.getItemId(), cartProductDto);

            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            //数据库获取数据异常
            addCartResponse.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            addCartResponse.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return addCartResponse;
    }

    /**
     * @return : 如果返回的为null代表失败【redis无此数据等原因】，正常结束的话，返回200
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse updateCartNumResponse = new UpdateCartNumResponse();

        RMap map = RedisUtils.redisOfGetMap(client, String.valueOf(request.getUserId()));
        if (map == null || map.size() == 0) {
            return null;
        }

        // 如果没有该条记录返回的是null
        CartProductDto productInfo = (CartProductDto) map.get(request.getItemId());
        if (productInfo == null) {
            return null;
        }

        int number = request.getNum();
        productInfo.setProductNum((long) number);
        productInfo.setChecked(request.getChecked());

        // map不能覆盖只能先删后添加
        map.replace(request.getItemId(), productInfo);

        updateCartNumResponse.setCode("200");
        updateCartNumResponse.setMsg("操作成功");
        return updateCartNumResponse;
    }

    /***
     * 购物车的内容的全选，注意购物车如果为空的情况
     */
    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();
        response.setCode("500");
        response.setMsg("fail");
        RMap map = RedisUtils.redisOfGetMap(client, String.valueOf(request.getUserId()));

        if (map == null || map.size() == 0) {
            return response;
        }

        for (Object keyValue : map.keySet()) {
//            Long key = (Long) keyValue;
            CartProductDto value = (CartProductDto) map.get(keyValue);
            // 数据异常的情况，如果没有对应的key-value,通过key拿到的就是null
            if (value == null) {
                return response;
            }
            value.setChecked(request.getChecked());
            map.put(keyValue, value);
        }

        response.setCode("200");
        response.setMsg("success");
        return response;
    }

    /***
     * @param request:userID,pid[商品Id]
     * @return : 如果userId,getItemId不存在，或者购物车中没有数据，直接返回null，不用执行后面的代码，
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {

        DeleteCartItemResponse response = new DeleteCartItemResponse();
        response.setCode("200");
        response.setMsg("success");


        if (request.getUserId() == null || request.getItemId() == null) {
            return response;
        }

        RMap map = RedisUtils.redisOfGetMap(client, String.valueOf(request.getUserId()));
        if (map == null || map.size() == 0) {
            return response;
        }
        map.remove(request.getItemId());

        return response;
    }

    /***
     * @param request : 根据里面的userId删除用户所有的购物车中的商品
     * @return : 返回值不重要，不管如何，一定会成功的操作。
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {

        if (request.getUserId() == null) {
            return null;
        }
        RMap<Long, CartProductDto> map = RedisUtils.redisOfGetMap(client, String.valueOf(request.getUserId()));
        if (map == null || map.size() == 0) {
            return null;
        }

        // 删除选中
        for (Long key : map.keySet()) {
            CartProductDto value = map.get(key);
            if (value.getChecked().equals("true")) {
                map.remove(key);
            }
        }
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        response.setCode("200");
        response.setMsg("success");
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        if (request.getUserId() == null) {
            return null;
        }
        RMap<String, CartProductDto> map = RedisUtils.redisOfGetMap(client, String.valueOf(request.getUserId()));
        List<Long> productIds = request.getProductIds();
        for (Long productId : productIds) {
            map.remove(productId);
        }

        ClearCartItemResponse clearCartItemResponse = new ClearCartItemResponse();
        clearCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        clearCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return clearCartItemResponse;

    }
}
